const {
  queryAssetsByUserAndType
} = require('../../api/workOrder')
const { clearEmptyKey } = require('../../utils/clearEmptyKey')
const {
  to,
  openLoading,
  closeLoading
} = getApp()
Page({
  data: {
    loadingType: '',
    dataList: [],
    pagination: {
      page: 1,
      limit: 10
    },
    total: 0
  },

  onLoad() {
    this.resetData()
    this.getQuaryAsserts()
  },

  async getQuaryAsserts(openL = true) {
    const params = {
      userId: this.options.userId,
      assetsTypeId: this.options.assetsTypeId,
      ...this.data.pagination
    }

    clearEmptyKey(params)

    openL && openLoading()
    const [err, data] = await to(queryAssetsByUserAndType(params))
    closeLoading()
    if (!err) {
      const {
        dataList
      } = this.data
      this.setData({
        dataList: dataList.concat(data.dataList),
        total: data.total
      })

      if (data.total === 0) {
        this.setData({
          loadingType: 'empty'
        })
        return
      }

      if (this.data.dataList.length >= data.total) {
        this.setData({
          loadingType: 'end'
        })
      }
    }
  },

  handleScrolltolower() {
    const {
      total,
      pagination,
      dataList
    } = this.data

    if (dataList.length < total) {
      let page = pagination.page;
      page++
      this.setData({
        loadingType: 'loading',
        ['pagination.page']: page
      })
      this.getQuaryAsserts(false)
    }
  },

  resetData() {
    this.setData({
      ['pagination.page']: 1,
      dataList: [],
      loadingType: '',
      total: 0
    })
  },

  handleChoose(event) {
    const currentData = event.detail
    const pages = getCurrentPages();
    const parentPages = pages[pages.length - 2];
    parentPages.setDeviceData({
      ['formData.assetsId']: currentData.assetsId,
      ['formData.assetsName']: currentData.assetsName
    })

    wx.navigateBack()
  }
})